package com.gtone.usbtool.datatool;

import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Environment;
import android.util.Log;
import android.widget.Toast;

import com.gtone.usbtool.bean.EncryptCode;

import java.io.File;

public class DataBaseTool {
    private SQLiteDatabase database = null;
    private final Context mContext;

    public DataBaseTool(Context mContext) {
        this.mContext = mContext;
        buildDB();
    }

    private void buildDB() {
        // 生成 helper 对象，可以打开数据库文件。文件名可以是相对路径或绝对路径
        File file = new File(Environment.getExternalStorageDirectory().getPath() + "/efb/databases/usbEncrypt.db");
        if (!file.exists()) {
            Toast.makeText(mContext, "数据库创建失败，请检查APP是否取得了存储的读写权限", Toast.LENGTH_SHORT).show();
            return;
        }

        SDSQLiteOpenHelper sdsqLiteOpenHelper = new SDSQLiteOpenHelper(mContext, "/efb/databases/usbEncrypt.db", null, 1) {
            @Override
            public void onCreate(SQLiteDatabase db) {
                createTable();
            }

            @Override
            public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

            }
        };

        database = sdsqLiteOpenHelper.getWritableDatabase();
    }

    //create table if not exists
    private void createTable() {
        String sql = "create table if not exists encrypt_code(id integer primary key autoincrement,show_code varchar(20),password varchar(20))";
        if (database != null) {
            database.execSQL(sql);
        }
    }

    public EncryptCode randomData() {
        EncryptCode encryptCode = new EncryptCode();
        //创建游标对象
        Cursor cursor = database.query("encrypt_code", new String[]{"id", "show_code", "password"}, "id=?",
                new String[]{String.valueOf(randomNum())}, null, null, null);
        //利用游标遍历所有数据对象
        while (cursor.moveToNext()) {
            @SuppressLint("Range")
            String showCode = cursor.getString(cursor.getColumnIndex("show_code"));
            @SuppressLint("Range")
            String password = cursor.getString(cursor.getColumnIndex("password"));
            encryptCode.setKey(showCode);
            encryptCode.setValue(password);
        }
        // 关闭游标，释放资源
        cursor.close();

        Log.d("随机数据", encryptCode.toString());
        return encryptCode;
    }

    /**
     * 在所有数据内随机一条数据的脚标
     */
    private int randomNum() {
        return (int) (Math.random() * allCaseNum());
    }

    /**
     * 查询数据库中的总条数.
     *
     * @return
     */
    public long allCaseNum() {
        String sql = "select count(*) from encrypt_code";
        Cursor cursor = database.rawQuery(sql, null);
        cursor.moveToFirst();
        long count = cursor.getLong(0);
        cursor.close();
        return count;
    }

}
